<?php
/**
 * Created by PhpStorm.
 * User: 1
 * Date: 2017-07-10
 * Time: 15:04
 */

namespace app\index\command;


use app\index\helper\CommandHelper;
use app\src\base\helper\ValidateHelper;
use app\src\email\action\EmailSendAction;
use app\src\sunsun\common\logic\UserDeviceLogic;
use app\src\sunsun\filterVat\action\FilterVatDeviceEventAction;
use app\src\sunsun\filterVat\action\FilterVatTcpLogAction;
use app\src\sunsun\filterVat\logic\FilterVatDeviceEventLogic;
use app\src\sunsun\filterVat\logic\FilterVatDeviceLogic;
use app\src\sunsun\filterVat\model\FilterVatDeviceEvent;
use app\src\user\logic\UcenterMemberLogic;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;

class FilterVatCommand extends Command
{

    protected function initialize(Input $input, Output $output)
    {
        CommandHelper::loadLang(['zh-cn', 'en', 'zh-tw']);
    }

    protected function configure()
    {
        $this->setName('device:filter_vat')
            ->addOption('interval', '', Option::VALUE_OPTIONAL, 'device event process sleep {interval} seconds', 30)
            ->addOption('size', '', Option::VALUE_OPTIONAL, 'device event process sizes per time', 10)
            ->addOption('type', '', Option::VALUE_OPTIONAL, 'command type, support (process_event,offline,clear)', 'clear')
            ->setDescription('filter_vat device event process');
    }

    protected function execute(Input $input, Output $output)
    {
        $size = $input->getOption('size');
        $type = $input->getOption('type');
        $interval = $input->getOption('interval');
        $output->info('type= ' . $type . ' size=' . $size);

        switch (strtolower($type)) {
            case 'process_event':
                $this->process_event($output, $size, $interval);
                break;
            case 'offline':
                $this->offline($output, $size);
                break;
            case 'clear':
                $this->clear($output);
                break;
            default:
                $this->clear($output);
                break;
        }
    }

    private function process_event(Output $output, $size, $interval)
    {
        //
        $userDeviceLogic = new UserDeviceLogic();
        $ucenterMemberLogic = new UcenterMemberLogic();
        $deviceEventLogic = new FilterVatDeviceEventLogic();
        while (true) {
            sleep($interval);
            $output->info('process');
            $page = ['curpage' => 1, 'size' => $size];
            $result = $deviceEventLogic->query(['pro_status' => FilterVatDeviceEvent::PRO_STATUS_NOT_PROCESS], $page, "id asc");

            $list = $result['info']['list'];
            $allEntity = [];
            $now = time();

            foreach ($list as $item) {
                $id = $item['id'];
                $did = $item['did'];
                $eventType = $item['event_type'];
                $entity = ['id' => $id, 'update_time' => $now, 'pro_status' => 1];
                array_push($allEntity, $entity);

                $time = $item['create_time'];

                //最多取10个，一台设备被50个人以上绑定的情况不处理，效率
                $result = $userDeviceLogic->query(['did' => $did], ['curpage' => 1, 'size' => 50]);

                if (ValidateHelper::legalArrayResult($result)) {
                    $list = $result['info']['list'];
                    $ctrl_pwd = CommandHelper::getCtrlPwd($did, new FilterVatDeviceLogic());
                    foreach ($list as $deviceItem) {
                        $uid = $deviceItem['uid'];
                        $timezone = intval($deviceItem['timezone']);
                        $lang = $deviceItem['lang'];
                        $extra = json_decode($deviceItem['extra'], JSON_OBJECT_AS_ARRAY);
                        if (!is_array($extra) || !array_key_exists("pwd", $extra) || ($extra['pwd'] != 'sunsun123456' && $extra['pwd'] != $ctrl_pwd)) {
                            // 密码不一致就不需要处理

                            continue;
                        }
                        $notify_email = array_key_exists('notify_email', $extra) ? intval($extra['notify_email']) : 0;

                        $localTime = gmdate('H:i:s', $timezone * 3600 + $time);
                        $nickname = $deviceItem['device_nickname'];

                        $result = $ucenterMemberLogic->getInfo(['id' => $uid]);
                        $member = $result['info'];
                        if (ValidateHelper::legalArrayResult($result)) {
                            $content = lang('filter_event_type_' . $eventType, '', $lang);
                            $email = $member['email'];
                            $data = [
                                'to_email' => $email,
                                'title' => lang('device_notify_title', ['nickname' => $nickname, 'device_type' => lang('filter', [], $lang)], $lang),
                                'content' => lang('device_notify_content', ['nickname' => $nickname, 'time' => $localTime, 'content' => $content], $lang)
                            ];
                            if ($notify_email == 1) {// 等于1 才进行邮件推送
                                $output->info('email send');
                                $result = (new EmailSendAction())->send($data['to_email'], $data['title'], $data['content'], CommandHelper::$pondLinkEmail);
                                if (!$result['status']) {
                                    $output->error('email send error=' . json_encode($result['info']));
                                }
                            }
                            $data['to_uid'] = $uid;

                            if ($time > time() - 1800) {
                                CommandHelper::pushUMeng($data);
                            }
                        }
                    }
                }
            }

            // 统一更新
            if (count($allEntity) > 0) {
                $result = (new FilterVatDeviceEventLogic())->saveAll($allEntity);
                if ($result['status']) {
                    $output->info(' save_all = ' . count($result['info']));
                } else {
                    $output->info(' save_all error = ' . $result['info']);
                }
            }
        }

    }

    private function offline(Output $output, $size = 10)
    {
        $time = microtime(true);
        $output->info('offline start');
        $result = CommandHelper::offline_notify($size, new FilterVatDeviceLogic(), 'filter');
        $cost_time = microtime(true) - $time;
        if ($result['status']) {
            $cnt = count($result['info']);
            $output->info('effect ' . $cnt);
        }
        $output->info('cost ' . $cost_time . ' s');
        $output->info('offline end');
    }


    private function clear(Output $output)
    {
        $output->highlight('filter_vat clear start');
        //1. tcp接口日志
        $now = time();
        $dataTimestamp = $now - 3 * 3600;
        (new FilterVatTcpLogAction())->clearExpiredData($dataTimestamp);

        //2. 事件日志
        $dataTimestamp = $now - 10 * 3600;
        (new FilterVatDeviceEventAction())->clearExpiredData($dataTimestamp);

        $output->highlight('filter_vat clear end');
    }
}